<?php

namespace app\order\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\api\logic\ApiOrderLogic;
use app\data\util\HttpUtil;
use app\order\logic\OrderLogic;

class CheckbillLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\order\model\Order();
    }

    //每月物流账单核对重量金额跟总运费
    public function MonthlyLogisticsBillVerification(){
        //查询17track物流轨迹状态
        // $this->QueryTheStatusOfLogisticsTrajectory_sdh();die;
        // $this->QueryTheStatusOfLogisticsTrajectory_111();die;
        // $this->QueryTheStatusOfLogisticsTrajectory();die;
        //全球无忧
        $this->checkbill_qqwynew();
        // $this->checkbill_qqwyold();
        // $this->checkbill_logistics();
        // 顺丰
        // $this->checkbill_sf();
        //闪电猴
        // $this->checkbill_sdh();
        //递四方
        // $this->checkbill_4px();
    }

    //sdh
    public function QueryTheStatusOfLogisticsTrajectory_sdh(){
        // $deletes = Db::name('ordercheck_logistics_sdh')
        //     ->where('LogisticsStatus',"like","%Delivered_Other%")
        //     ->delete();
        // halt($deletes);
        $update['status'] = 0;
        $updates = Db::name('ordercheck_logistics_sdh')
            ->where('LogisticsStatus',"like","%17track无消息，系统状态：无%")
            // ->where('LogisticsStatus',"like","%注册%")
            ->update($update)                                  ;
        halt($updates);

        $t1       = microtime(true);
        $count = Db::name('ordercheck_logistics_sdh')
            ->where('status',0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('ordercheck_logistics_sdh')
                ->where('status',0)
                // ->where('transfer_number',"SDH0066020939")
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                //方法2 查询17track物流轨迹状态
                $status = $this->trackLogisticsTrajectory($v['transfer_number']);
                $order_achievement['LogisticsStatus'] = $status ?? "";
                // halt($order_achievement);
                if(isset($order_achievement['LogisticsStatus']) && !empty($order_achievement['LogisticsStatus'])){
                    //方法1 数据库查询物流轨迹状态
                    if($order_achievement['LogisticsStatus'] == '注册完成等待17track消息'){
                        $order_achievement = Db::name('order_achievement')->where('tracking_number',$v['transfer_number'])->find();
                        $order_achievement['LogisticsStatus'] = $order_achievement['LogisticsStatus'] ?? "无";
                        $order_achievement['LogisticsStatus'] = "17track无消息，系统状态：".$order_achievement['LogisticsStatus'];
                    }
                    $v['status'] = 1;
                    Db::name('ordercheck_logistics_sdh')->where('id',$v['id'])->update(
                        [
                            'status'=>1,
                            'LogisticsStatus'=>$order_achievement['LogisticsStatus']
                        ]
                    );
                }else{
                    $v['status'] = 2;
                    Db::name('ordercheck_logistics_sdh')->where('id',$v['id'])->update(['status'=>2]);
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    //查询17track物流轨迹状态
    public function QueryTheStatusOfLogisticsTrajectory(){
        // $update['status'] = 0;
        // $updates = Db::name('ordercheck_logistics')
        //     ->where('date',"2024-10")
        //     ->where(`LogisticsStatus`,"LIKE" , '%无%')
        //     ->update($update);
        // halt($updates);

        $t1       = microtime(true);
        $count = Db::name('ordercheck_logistics')
            ->where('date',"2024-10")
            ->where('status',0)
            ->where('tracking_company_number',3)//特殊情况--使用菜鸟渠道进行查询
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('ordercheck_logistics')
                ->where('date',"2024-10")
                ->where('status',0)
                ->where('tracking_company_number',3)
                // ->where('transfer_number','HFUS00199969')
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                //方法2 查询17track物流轨迹状态
                // $v['transfer_number'] = '4203028492612903396184000023796439';
                $status = $this->trackLogisticsTrajectory($v['transfer_number']);
                $order_achievement['LogisticsStatus'] = $status ?? "";
                // halt($order_achievement);
                if(isset($order_achievement['LogisticsStatus']) && !empty($order_achievement['LogisticsStatus'])){
                    //方法1 数据库查询物流轨迹状态
                    if($order_achievement['LogisticsStatus'] == '注册完成等待17track消息'){
                        $order_achievement = Db::name('order_achievement')->where('tracking_number',$v['transfer_number'])->find();
                        $order_achievement['LogisticsStatus'] = $order_achievement['LogisticsStatus'] ?? "无";
                        $order_achievement['LogisticsStatus'] = "17track无消息，系统状态：".$order_achievement['LogisticsStatus'];
                    }
                    $v['status'] = 1;
                    Db::name('ordercheck_logistics')->where('id',$v['id'])->update(
                        [
                            'status'=>1,
                            'LogisticsStatus'=>$order_achievement['LogisticsStatus']
                        ]
                    );
                }else{
                    $v['status'] = 2;
                    Db::name('ordercheck_logistics')->where('id',$v['id'])->update(['status'=>2]);
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //查询17track物流轨迹状态
    public function QueryTheStatusOfLogisticsTrajectory_111(){
        // $update['status'] = 0;
        // $updates = Db::name('checkbill_333_12')
        //     ->where('LogisticsStatus',"like","%InTransit_Other%")
        //     // ->where('LogisticsStatus',"like","%17track无消息，系统状态：无%")
        //     // ->where('LogisticsStatus',"like","%注册%")
        //     // ->where('LogisticsStatus',"=","17track无消息，系统状态：")
        //     ->update($update);
        // halt($updates);

        $t1       = microtime(true);
        $count = Db::name('checkbill_333_12')
            ->where('status',0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_333_12')
                ->where('status',0)
                // ->where('id',491070)
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                //方法2 查询17track物流轨迹状态
                $status = $this->trackLogisticsTrajectory($v['waybill_no']);
                $order_achievement['LogisticsStatus'] = $status ?? "";
                // halt($order_achievement);
                if(isset($order_achievement['LogisticsStatus']) && !empty($order_achievement['LogisticsStatus'])){
                    //方法1 数据库查询物流轨迹状态
                    if($order_achievement['LogisticsStatus'] == '注册完成等待17track消息'){
                        $order_achievement = Db::name('order_achievement')->where('tracking_number',$v['waybill_no'])->find();
                        $order_achievement['LogisticsStatus'] = $order_achievement['LogisticsStatus'] ?? "无";
                        $order_achievement['LogisticsStatus'] = "17track无消息，系统状态：".$order_achievement['LogisticsStatus'];
                    }
                    $v['status'] = 1;
                    Db::name('checkbill_333_12')->where('id',$v['id'])->update(
                        [
                            'status'=>1,
                            'LogisticsStatus'=>$order_achievement['LogisticsStatus']
                        ]
                    );
                }else{
                    $v['status'] = 2;
                    Db::name('checkbill_333_12')->where('id',$v['id'])->update(['status'=>2]);
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function trackLogisticsTrajectory($transfer_number)
    {
        $data = array();
        $data['number'] = $transfer_number;
        $data2[] = $data;
        $url = "https://api.17track.net/track/v2.2/gettrackinfo";
        $return = HttpUtil::trackPostUrl($url, $data2);
        if(empty($return)){
            $return = $this->web_register($transfer_number);
            $status = "注册完成等待17track消息";
        }else{
            //未注册
            $Unregistered = $return['data']['rejected'][0]['error']['message'] ?? "";
            if(!empty($Unregistered)){
                // echo $Unregistered;
                $return = $this->web_register($transfer_number);
                $status = "正在注册";
            }else{
                $status = $return['data']['accepted'][0]['track_info']['latest_status']['status'] ?? "";
                $time_iso = $return['data']['accepted'][0]['track_info']['latest_event']['time_iso'] ?? "";
                $test = [
                    'status' => $status,
                    'time_iso' => $time_iso
                ];
                // return $test;
            }
        }
        // halt($status);
        return $status;
    }


    /**
     * @desc   获取物流轨迹数据
     * @author xx
     * @date 2024-12-28
     */
    public function get_track_info($track_number){
        $url    =  Config('Logisticskey.track_info.track_url');
        $params = ['number'=>$track_number];
        $return = HttpUtil::trackPostUrl($url, [$params]);
        $list               = $return['data']['accepted'][0]['track_info']??[];
        //接收地址;
        $recipient_address  = $list['shipping_info']['recipient_address']['country']??'';
        //最新的物流主状态;
        $latest_status      =  $list['latest_status']['status']??'';
        //最新物流子状态;
        $latest_sub_status  =  $list['latest_status']['sub_status']??'';

        //发送提供的物流商和国家;
        $tracking_provider_country = $list['tracking']['providers'][0]['provider']['country']??'';
        $tracking_provider_name    = $list['tracking']['providers'][0]['provider']['name']??'';
        //tracking数组;
        $tracking_info             = [];
        $tracking_list             = $list['tracking']['providers'][0]['events']??'';
        if($tracking_list){
              foreach($tracking_list as $v){
                  $temp['time_raw']    = updatetime_automatic_date($v['time_iso']);
                  $temp['location']    = $v['location'];
                  $temp['description'] = $v['description'];
                  $temp['sub_status']  = $v['sub_status'];
                  $tracking_info[]     = $temp;
              }
        }

        //数据组装;
        return [
            'provider_country' =>$tracking_provider_country,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$recipient_address,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'tracking_list'    =>$tracking_info,
        ];
    }





    //注册17track
    public function MonthlyLogisticsBillVerification2()
    {
        $t1       = microtime(true);
        $count = Db::name('ordercheck_logistics')
            ->where('date',"2024-11")
            ->where('status',2)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('ordercheck_logistics')
                ->where('date',"2024-11")
                ->where('status',2)
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                $return = $this->web_register($v['transfer_number']);
                $msg = $return['data']['rejected'][0]['error']['message'] ?? "";
                if($msg !== ""){
                    $v['status'] = 0;
                    Db::name('ordercheck_logistics')->where('id',$v['id'])->update(['status'=>0]);
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页,信息'.$msg . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function web_register($transfer_number)
    {
        $data = array();
        $data['number'] = $transfer_number;
        $data2[] = $data;
        $url = "https://api.17track.net/track/v2.2/register";
        $return = HttpUtil::trackPostUrl($url, $data2);
        return $return;
    }

    //全球无忧对账
    public function checkbill_logistics(){
        $t1       = microtime(true);
        $count = Db::name('ordercheck_logistics')
            ->where('date',"2025-05")
            ->where('tracking_company_number',5)
            ->where('status',0)
            ->where('transfer_number',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('ordercheck_logistics')
                ->where('date',"2025-05")
                ->where('tracking_company_number',5)
                ->where('status',0)
                ->where('transfer_number',">",0)
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                $order = Db::name('order_achievement')->field('skuquantity')->where('tracking_number',$v['transfer_number'])->find();
                $update = [
                    'skuquantity' => $order['skuquantity'] ?? 0,
                    'status' => 1,
                ];
                Db::name('ordercheck_logistics')
                    ->where('id',$v['id'])
                    ->update($update); 
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //全球无忧对账
    public function checkbill_qqwynew(){
        $t1       = microtime(true);
        $count = Db::name('checkbill_qqwynew')
            // ->where('id',21)
            ->where('reconciliation_status',0)
            ->where('waybill_no',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_qqwynew')
                // ->where('id',21)
                ->where('reconciliation_status',0)
                ->where('waybill_no',">",0)
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                // $order_fulfillments = Db::name('order_fulfillments')->where('tracking_number',$v['waybill_no'])->find();
                // $order_id = $order_fulfillments['order_id'] ?? 0;
                // if($order_id > 0){
                //     $order = Db::name('order_achievement')->where('order_id',$order_id)->find();
                // }else{
                //     $order = Db::name('order_achievement')->where('tracking_number',$v['waybill_no'])->find();
                // }
                // if(empty($order)){
                    // $order = Db::name('order_achievement')->where('order_id',$v['waybill_no'])->find();
                // }
                // halt($order);


                //tiktok的订单
                // $order = Db::name('test4')->where('order_id',$v['waybill_no'])->find();

                //海外仓订单
                $tik_auto_shipping = Db::name('tik_auto_shipping')->where('deliver_no',$v['waybill_no'])->find();
                $skus = $tik_auto_shipping['sku'] ?? "";
                if(!empty($skus)){
                    //查看有几个逗号
                    $counta = substr_count($skus, ',');
                    $order['skuquantity'] = $counta+1;
                }
                
                $update = [
                    'pieces_new' => $order['skuquantity'] ?? 0,
                    'reconciliation_status' => 1,
                ];
                Db::name('checkbill_qqwynew')
                    ->where('id',$v['id'])
                    ->update($update); 
                // $this->checkbill_qqwyinfo($v);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    //全球无忧对账
    public function checkbill_qqwyold(){
        $t1       = microtime(true);
        $count = Db::name('checkbill_qqwy')
            // ->where('id',7)
            ->where('reconciliation_status',0)
            // ->where('waybill_no',">",0)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_qqwy')
                // ->where('id',7)
                ->where('reconciliation_status',0)
                // ->where('waybill_no',">",0)
                ->limit(500)
                ->order('id desc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                //如果waybill_no为空 则查找上一条
                if(empty($v['waybill_no'])){
                    $id_new = $v['id'] - 1;
                    $qqwy_new = Db::name('checkbill_qqwy')->where('id',$id_new)->find();
                    $v['waybill_no'] = $qqwy_new['waybill_no'];
                }
                if(empty($v['waybill_no'])){
                    $id_new = $v['id'] - 2;
                    $qqwy_new = Db::name('checkbill_qqwy')->where('id',$id_new)->find();
                    $v['waybill_no'] = $qqwy_new['waybill_no'];
                }
                if(empty($v['waybill_no'])){
                    $id_new = $v['id'] - 3;
                    $qqwy_new = Db::name('checkbill_qqwy')->where('id',$id_new)->find();
                    $v['waybill_no'] = $qqwy_new['waybill_no'];
                }
                if(empty($v['waybill_no'])){
                    echo PHP_EOL . "物流单号为空" . PHP_EOL;die;
                }
                $order = Db::name('order_achievement')->where('tracking_number',$v['waybill_no'])->find();
                if(!empty($order)){
                    $order_info = Db::name('order_skuinfo')
                        ->where('order_id',$order['order_id'])
                        ->where('new_sku',$v['fnsku'])
                        ->find();
                }
                $update = [
                    'zone_id_new' => $order_info['realcount'] ?? 0,
                    'pieces_new' => $order['skuquantity'] ?? 0,
                    'skus' => $order['sku'] ?? 0,
                    'reconciliation_status' => 1,
                ];
                // halt($update);
                Db::name('checkbill_qqwy')
                    ->where('id',$v['id'])
                    ->update($update); 
                // $this->checkbill_qqwyinfo($v);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function checkbill_qqwyinfo($checkbill_qqwy)
    {
        // $checkbill_qqwy['reference_no'] = trim($checkbill_qqwy['reference_no']);
        // $checkbill_qqwy['postal'] = trim($checkbill_qqwy['postal']);
        // $checkbill_qqwy['total_weight'] = trim($checkbill_qqwy['total_weight']);
        // //分区
        // $postal = (int)substr($checkbill_qqwy['postal'],0,3);
        // $recon_qqwy_zone = Db::name('checkbill_qqwyzone')
        //     ->where('postal_code_start',"<=",$postal)
        //     ->where('postal_code_end',">=",$postal)
        //     ->find();
        // $zone_id_new = 0;
        // if(!empty($recon_qqwy_zone)){
        //     $zone_id_new = $recon_qqwy_zone['zone_id'];
        // }
        //分区结束

        //总重量
        //件数
        $order_achievement = Db::name('order_achievement')->where('tracking_number',$checkbill_qqwy['waybill_no'])->find();
        $checkbill_qqwy['reference_no'] = $order_achievement['order_id']??'';
        $total_weight_new = 0;
        $pieces_new = 0;
        if(!empty($checkbill_qqwy['reference_no'])){
            $info = Db::name('order_skuinfo')
                ->field('a.spu,sku_id, new_sku,a.count as qtyOrdered,b.quantity')
                ->alias('a')
                ->join('qu_order_info b','b.order_id = a.order_id and b.variant_id = a.sku_id', 'left')
                ->where('a.order_id', $checkbill_qqwy['reference_no'])
                ->group('a.id,b.info_id')
                ->select()
                ->toarray();
                
            $outputArray = [];
            foreach ($info as $item) {
                $sku = $item['new_sku'];
                if (isset($outputArray[$sku])) {
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$sku]['qtyOrdered'] += $qtyOrdered;
                } else {
                    $outputArray[$sku] = $item;
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$sku]['qtyOrdered'] = $qtyOrdered;
                }
            }
            $OrderDetail3 = array_values($outputArray);
            if(!empty($OrderDetail3)){
                // $skus = array_column($OrderDetail3,'new_sku');

                // $weightInfo = Db::name('checkbill_qqwyskuweight')->where([
                //     'new_sku' => $skus
                // ])->field('new_sku,weight')->select()->toArray();
                // $weightInfoMap = array_column($weightInfo,null,'new_sku');
                $info          = array_column($OrderDetail3,null,'new_sku');
                foreach($info as $v){
                    // $weightValues       = $weightInfoMap[$v['new_sku']]??[];
                    // if(empty($weightValues)){
                    //     $product = Db::name('product')
                    //         ->where('spu',$v['spu'])
                    //         ->find();
                    //     if(isset($product) && $product['max_weight'] > 0.01){
                    //         $weightValues['weight'] = (float)number_format($product['max_weight']*1000, 2, '.', '');
                    //     }
                    // }
                    // if(empty($weightValues)){
                    //     $msg = "添加重量信息失败:".$v['spu']."";
                    //     // halt($msg);
                    //     $weightValues['weight'] = 0;
                    // }
                    
                    // $weight             = isset($weightValues['weight'])&&$weightValues['weight'] ? intval($weightValues['weight']*$v['qtyOrdered']) : 0;
                    
                    // $total_weight_new        +=(float)$weight;
                    $pieces_new           +=$v['qtyOrdered'];
                }
            }
        }
        //件数结束
        //总重量结束
        //运费
        // $operating_fee_news = 0;
        // if(!empty($total_weight_new)){
        //     //运费-程序计算
        //     $total_weight_new = (float)number_format($total_weight_new/1000, 2, '.', '');
        //     $recon_qqwy_zoneweight = Db::name('checkbill_qqwyzoneweight')
        //         ->where('weight_range_star',"<=",$total_weight_new)
        //         ->where('weight_range_end',">=",$total_weight_new)
        //         ->where('zone_id',"=",$zone_id_new)
        //         ->find();
        //     if(!empty($recon_qqwy_zoneweight)){
        //         $operating_fee_news = $recon_qqwy_zoneweight['freight_cost'];
        //     }
        // }
        //运费结束

        $update = [
            // 'zone_id_new' => $zone_id_new,
            // 'total_weight_new' => $total_weight_new,
            'pieces_new' => $pieces_new,
            // 'operating_fee_news' => $operating_fee_news,
            'reconciliation_status' => 1,
            // 'zone_id_new' => $zone_id_new,
        ];
        $return = Db::name('checkbill_qqwy')
            ->where('id',$checkbill_qqwy['id'])
            ->update($update); 
        return $return;
    }
    

    //全球无忧对账
    public function checkbill_sf(){
        $t1       = microtime(true);
        $count = Db::name('checkbill_sf')
            ->where('reconciliation_status',0)
            // ->where('id',141)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_sf')
                ->where('reconciliation_status',0)
                // ->where('id',141)
                ->limit(500)
                ->order('id asc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                $this->checkbill_sfinfo($v);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //闪电猴对账
    public function checkbill_sdh(){
//         $update['reconciliation_status'] = 0;
//         $list = Db::name('checkbill_sdh')
//                 ->where('total_weight_new',"=",0)
//                 ->update($update);
// halt($list);

        $t1       = microtime(true);
        $count = Db::name('checkbill_sdh')
            ->where('reconciliation_status',0)
            // ->where('id',141)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_sdh')
                ->where('reconciliation_status',0)
                // ->where('id',141)
                ->limit(500)
                ->order('id asc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                $order = Db::name('order_achievement')->where('tracking_number',$v['waybill_no'])->find();
                $update = [
                    'pieces_new' => $order['skuquantity'] ?? 0,
                    'reconciliation_status' => 1,
                ];
                Db::name('checkbill_sdh')
                    ->where('id',$v['id'])
                    ->update($update); 
                // return $return;
                // $this->checkbill_sdhinfo($v);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //4px对账
    public function checkbill_4px(){
//         $update['reconciliation_status'] = 0;
//         $list = Db::name('checkbill_qqwy')
//                 ->where('id',">",0)
//                 ->update($update);
// halt($list);

        $t1       = microtime(true);
        $count = Db::name('checkbill_4px')
            ->where('reconciliation_status',0)
            // ->where('id',28473)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('checkbill_4px')
                ->where('reconciliation_status',0)
                // ->where('id',28473)
                ->limit(500)
                ->order('id asc')
                ->select()
                ->toArray();
            
            foreach ($list as $v){
                $order = Db::name('order_achievement')->where('tracking_number',$v['waybill_no'])->find();
                $update = [
                    'pieces_new' => $order['skuquantity'] ?? 0,
                    'reconciliation_status' => 1,
                ];
                Db::name('checkbill_4px')
                    ->where('id',$v['id'])
                    ->update($update); 
                // $this->checkbill_4pxinfo($v);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
    * @desc    顺丰对账详情
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function checkbill_sfinfo($checkbill_sf)
    {
        if($checkbill_sf['code'] == "SELF_PICKUP_EXPRESS"){
            $return = Db::name('order')->where('order_id',$checkbill_sf['reference_no'])->find();
            $update['reconciliation_status'] = 2;
            if(isset($return) && !empty($return)){
                $update['reconciliation_status'] = 1;
            }
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
            return true;
        }
        //对账开始
        $checkbill_sf['reference_no'] = trim($checkbill_sf['reference_no']);
        $checkbill_sf['postal'] = trim($checkbill_sf['postal']);
        $checkbill_sf['total_weight'] = trim($checkbill_sf['total_weight']);
        $checkbill_sf['waybill_no'] = trim($checkbill_sf['waybill_no']) ?? 0;
        if(empty($checkbill_sf['reference_no'])){
            $order = Db::name('order')->where('tracking_number',$checkbill_sf['waybill_no'])->find();
            $checkbill_sf['reference_no'] = $order['order_id'] ?? 0;
        }
        $return = $this->get_order_check($checkbill_sf['reference_no']);
        
        //折后运费
        if(isset($return['total_weight']) && !empty($return['total_weight'])){
            $return['total_weight'] = (float)number_format($return['total_weight']*1000, 2, '.', '');
        }else{
            $update = [];
            $update['reconciliation_status'] = 2;
            Db::name('checkbill_sf')
                ->where('id',$checkbill_sf['id'])
                ->update($update);
        }
        //分区
        $postal = (int)substr($checkbill_sf['postal'],0,3);  
        $recon_sf_zone = Db::name('checkbill_sfzone')
            ->where('postal_code_start',"<=",$postal)
            ->where('postal_code_end',">=",$postal)
            ->find();
        if(!empty($recon_sf_zone)){
            $checkbill_sf['zone_id'] = $recon_sf_zone['zone_id'];
        }
        //分区结束

        //运费-程序计算
        $discounted_shipping_new = 0;
        $checkbill_sfzoneweight = Db::name('checkbill_sfzoneweight')
            ->where('weight_range_star',"<=",$checkbill_sf['total_weight'])
            ->where('weight_range_end',">=",$checkbill_sf['total_weight'])
            ->where('zone_id',"=",$checkbill_sf['zone_id'])
            ->find();
        if(!empty($checkbill_sfzoneweight)){
            $discounted_shipping_new = $checkbill_sfzoneweight['freight_cost'];
        }

        //操作费   
        if(!isset($return['total_num'])){//超过10cm,操作费+2.57
            $return['total_num'] = 0;
        }
        if(!isset($return['type_menue'])){//超过10cm,操作费+2.57
            $return['type_menue'] = 0;
        }
        if(!isset($return['total_weight'])){//超过10cm,操作费+2.57
            $return['total_weight'] = 0;
        }

        $return['total_num'] = $return['total_num'] ?? 0;
        $operating_fee_news = 0;
        $multiple_pieces = $return['total_num'] - 1;//多件
        if($return['type_menue'] == 0){//一品
            $operating_fee_news = 3.24;
            if($multiple_pieces >=1){
                $operating_fee_news = (float)number_format($multiple_pieces*2.38+3.24, 2, '.', '');
            }
        }
        if($return['type_menue'] == 1){//多品
            $operating_fee_news = 3.24;
            if($multiple_pieces >=1){
                $operating_fee_news = (float)number_format($multiple_pieces*2.57+3.24, 2, '.', '');
            }
        }
        //最终数据
        $update = [
            'total_weight_new' => (float)number_format($return['total_weight']/1000, 2, '.', ''),
            'pieces_new' => $return['total_num'] ?? 0,
            'operating_fee_news' => $operating_fee_news,
            'discounted_shipping_new' => $discounted_shipping_new,
            'reconciliation_status' => 1,
            'zone_id_new' => $checkbill_sf['zone_id'],
        ];
        Db::name('checkbill_sf')
            ->where('id',$checkbill_sf['id'])
            ->update($update);
        return true;
    }

    //顺丰处理数据
    public function get_order_check($order_id=''){
        if(!$order_id) {
            // halt('order_id不能为空');
            return [];
        }  

        $result = Db::name('order_skuinfo')
            ->field('sku_id, new_sku,a.count as qtyOrdered,b.quantity')
            ->alias('a')
            ->join('qu_order_info b','b.order_id = a.order_id and b.variant_id = a.sku_id', 'left')
            ->where('a.order_id', $order_id)
            ->group('a.id,b.info_id')
            ->select()
            ->toarray();
        if(!$result) {
            // halt('暂无数据');
            return [];
        }  
        
        $list = self::getQtyOrdered($result);
        $total_info   = self::getTotalWeight($list);
        
        $total_weight = $total_info['totalWeight']??0;
        $total_num    = $total_info['totalNum']??0;
        $type_menue   = count($list) == 1 ? 0 : 1; //单品还是多品,0:单品  1:多品
        $total_height = self::getTotalHeight($list);
        return [
            'total_weight'=>$total_weight,
            'total_num'  =>$total_num,
            'total_height'=>$total_height,
            'type_menue'  =>$type_menue,
        ];
    }

    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info){
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['new_sku'];
            if (isset($outputArray[$sku])) {
                $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                $outputArray[$sku]['qtyOrdered'] += $qtyOrdered;
            } else {
                $outputArray[$sku] = $item;
                $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                $outputArray[$sku]['qtyOrdered'] = $qtyOrdered;
            }
        }
        return array_values($outputArray);
    }

    /**
     * @desc 获取发货总重量;
     * @author xx
     * @date 2024-02-22
     */
    public function getTotalWeight($OrderDetail3){
        if(!$OrderDetail3) return  0;
        $skus = array_column($OrderDetail3,'new_sku');
        //品牌不同的情况
        $skus = $skus[0];
        if(!empty($skus)){
            $pos = strpos($skus, '-');
            if ($pos !== false) {
                $skusArray = explode('-', $skus);
                // 获取黑色和尺码部分
                $skus = $skusArray[1] . '-' . $skusArray[2];
            }
        }

        if ($skus) {
            $where[] = ['new_sku', 'like', '%' . $skus . '%'];
        }
        
        $weightInfo = Db::name('checkbill_sfskuweight')->where($where)->field('new_sku,weight')->select()->toArray();
        // dump($skus);die;
        $weightInfoMap = array_column($weightInfo,null,'new_sku');
        $info          = array_column($OrderDetail3,null,'new_sku');
        $totalWeight   = 0;
        $totalNum      = 0;
        foreach($info as $v){
            $weightValues       = $weightInfoMap[$v['new_sku']]??[];
            $weight             = isset($weightValues['weight'])&&$weightValues['weight'] ? intval($weightValues['weight']*$v['qtyOrdered']) : 0;
            $totalWeight        +=$weight;
            $totalNum           +=$v['qtyOrdered'];
        }
        return ['totalWeight'=>$totalWeight,'totalNum'=>$totalNum];
    }


    /**
     * @desc 获取总高度
     */
    public function getTotalHeight($list){
        if(!$list) return  0;
        $skus = array_column($list,'new_sku');
        //品牌不同的情况
        $skus = $skus[0];
        if(!empty($skus)){
            $pos = strpos($skus, '-');
            if ($pos !== false) {
                $skusArray = explode('-', $skus);
                // 获取黑色和尺码部分
                $skus = $skusArray[1] . '-' . $skusArray[2];
            }
        }


        if ($skus) {
            $where[] = ['new_sku', 'like', '%' . $skus . '%'];
        }

        $info =Db::name('checkbill_sfskuweight')
            ->where($where)
            ->field('new_sku,heigth')
            ->select()
            ->toArray();
        if(!$info)  return 0;
        $totalHeight = 0;
        $info_map = array_column($info,null,'new_sku');
        foreach($list as $v){
            $heightValues       = $info_map[$v['new_sku']]??[];
            $height             = isset($heightValues['heigth'])&&$heightValues['heigth'] ? intval($heightValues['heigth']*$v['qtyOrdered']) : 0;
            $totalHeight        +=$height;
        }
        return  $totalHeight;
    }
    

    /**
    * @desc    闪电猴对账详情
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function checkbill_sdhinfo($checkbill_sdh)
    {
        $checkbill_sdh['waybill_no'] = trim($checkbill_sdh['waybill_no']);
        $order = Db::name('order')->where('tracking_number',$checkbill_sdh['waybill_no'])->find();
        $checkbill_sdh['reference_no'] = 0;
        if(!empty($order)){
            $checkbill_sdh['reference_no'] = $order['order_id'];
        }
        
        //总重量
        //件数
        $total_weight_new = 0;
        $pieces_new = 0;
        $spus_new = [];
        if(!empty($checkbill_sdh['reference_no'])){
            $info = Db::name('order_skuinfo')
                ->field('sku_id,a.spu,new_sku,a.count as qtyOrdered,b.quantity')
                ->alias('a')
                ->join('qu_order_info b','b.order_id = a.order_id and b.variant_id = a.sku_id', 'left')
                ->where('a.order_id', $checkbill_sdh['reference_no'])
                ->group('a.id,b.info_id')
                ->select()
                ->toarray();
            $outputArray = [];
            foreach ($info as $item) {
                $spu = $item['spu'];
                if (isset($outputArray[$spu])) {
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$spu]['qtyOrdered'] += $qtyOrdered;
                    $outputArray[$spu]['spu'] = $item['spu'];
                } else {
                    $outputArray[$spu] = $item;
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$spu]['qtyOrdered'] = $qtyOrdered;
                    $outputArray[$spu]['spu'] = $item['spu'];
                }
            }
            $OrderDetail3 = array_values($outputArray);
            if(!empty($OrderDetail3)){
                // $spus = array_column($OrderDetail3,'spu');
                if(!empty($OrderDetail3)){
                    // $spus = array_column($OrderDetail3,'spu');
                    // $weightInfo = Db::name('product')->where([
                    //     'spu' => $spus
                    // ])->field('spu,max_weight as weight')->select()->toArray();
                    // $weightInfoMap = array_column($weightInfo,null,'spu');
                    $info          = array_column($OrderDetail3,null,'spu');   
                    foreach($info as $v){
                        // $weightValues       = $weightInfoMap[$v['spu']]??[];
                        // $weight             = $weightValues['weight'] ?? 0;
                        // if($weight > 0 && $v['qtyOrdered'] >= 1){
                        //     $weight = (float)number_format((int)$v['qtyOrdered']*$weight, 3, '.', '');
                        // }
                        // $total_weight_new        +=(float)$weight;
                        $pieces_new           +=$v['qtyOrdered'];
                        $spus_new[]           =$v['spu'];
                    }
                }
            }
        }
        //件数结束
        $update = [
            'pieces_new' => $pieces_new,
            'reconciliation_status' => 1,
        ];
        if(empty($checkbill_sdh['reference_no'])){
            $update['reconciliation_status'] = 2;
        }
        $return = Db::name('checkbill_sdh')
            ->where('id',$checkbill_sdh['id'])
            ->update($update); 
        return $return;
        
        //总重量结束
        if(!empty($spus_new)){
            $spus_new = implode(',',$spus_new);
        }
        //运费
        $operating_fee_news = 0;
        if(!empty($total_weight_new)){
            //运费-程序计算
            // $total_weight_new = (float)number_format($total_weight_new/1000, 2, '.', '');
            $recon_qqwy_zoneweight = Db::name('checkbill_sdhweight')
                ->where('weight_range_star',"<=",$total_weight_new)
                ->where('weight_range_end',">=",$total_weight_new)
                ->find();
            if(!empty($recon_qqwy_zoneweight)){
                $operating_fee_news = (float)number_format($recon_qqwy_zoneweight['freight_cost']*$total_weight_new, 2, '.', '');
            }
        }
        //运费结束

        $update = [
            'total_weight_new' => $total_weight_new,
            'pieces_new' => $pieces_new,
            'operating_fee_news' => $operating_fee_news,
            'reconciliation_status' => 1,
            'sku' => $spus_new,
        ];
        if(empty($checkbill_sdh['reference_no'])){
            $update['reconciliation_status'] = 2;
        }  
        if($checkbill_sdh['total_weight_new'] > 0){
            // halt($update);
        }  
        
        $return = Db::name('checkbill_sdh')
            ->where('id',$checkbill_sdh['id'])
            ->update($update); 
        return $return;
    }

    /**
    * @desc    4px对账详情
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function checkbill_4pxinfo($checkbill_4px)
    {
        $checkbill_4px['waybill_no'] = trim($checkbill_4px['waybill_no']);
        $order = Db::name('order')->where('tracking_number',$checkbill_4px['waybill_no'])->find();
        $checkbill_4px['reference_no'] = 0;
        if(!empty($order)){
            $checkbill_4px['reference_no'] = $order['order_id'];
        } 
        //总重量
        //件数
        $total_weight_new = 0;
        $pieces_new = 0;
        $spus_new = [];
        if(!empty($checkbill_4px['reference_no'])){
            $info = Db::name('order_skuinfo')
                ->field('sku_id,a.spu,new_sku,a.count as qtyOrdered,b.quantity')
                ->alias('a')
                ->join('qu_order_info b','b.order_id = a.order_id and b.variant_id = a.sku_id', 'left')
                ->where('a.order_id', $checkbill_4px['reference_no'])
                ->group('a.id,b.info_id')
                ->select()
                ->toarray();
            $outputArray = [];
            foreach ($info as $item) {
                $spu = $item['spu'];
                if (isset($outputArray[$spu])) {
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$spu]['qtyOrdered'] += $qtyOrdered;
                    $outputArray[$spu]['spu'] = $item['spu'];
                } else {
                    $outputArray[$spu] = $item;
                    $qtyOrdered = (int)number_format($item['qtyOrdered'] * $item['quantity'], 0, '.', '');
                    $outputArray[$spu]['qtyOrdered'] = $qtyOrdered;
                    $outputArray[$spu]['spu'] = $item['spu'];
                }
            }
            $OrderDetail3 = array_values($outputArray);
            if(!empty($OrderDetail3)){
                $spus = array_column($OrderDetail3,'spu');
                $weightInfo = Db::name('product')->where([
                    'spu' => $spus
                ])->field('spu,max_weight as weight')->select()->toArray();
                $weightInfoMap = array_column($weightInfo,null,'spu');
                $info          = array_column($OrderDetail3,null,'spu');   
                foreach($info as $v){
                    $weightValues       = $weightInfoMap[$v['spu']]??[];
                    $weight             = $weightValues['weight'] ?? 0;
                    if($weight > 0 && $v['qtyOrdered'] >= 1){
                        $weight = (float)number_format((int)$v['qtyOrdered']*$weight, 3, '.', '');
                    }
                    
                    $total_weight_new        +=(float)$weight;
                    $pieces_new           +=$v['qtyOrdered'];
                    $spus_new[]           =$v['spu'];
                }
            }
        }
        //件数结束
        //总重量结束
        if(!empty($spus_new)){
            $spus_new = implode(',',$spus_new);
        }
        // halt($total_weight_new);
        //运费
        $operating_fee_news = 0;
        if(!empty($total_weight_new)){
            //运费-程序计算
            // $total_weight_new = (float)number_format($total_weight_new/1000, 2, '.', '');
            $operating_fee_news = (float)number_format($checkbill_4px['unit_price']*$total_weight_new, 2, '.', '');
        }
        //运费结束
        $update = [
            'total_weight_new' => $total_weight_new,
            'pieces_new' => $pieces_new,
            'operating_fee_news' => $operating_fee_news,
            'reconciliation_status' => 1,
            'sku' => $spus_new,
        ];

        if(empty($checkbill_4px['reference_no'])){
            $update['reconciliation_status'] = 2;
        }
        
        $return = Db::name('checkbill_4px')
            ->where('id',$checkbill_4px['id'])
            ->update($update); 
        return $return;
    }

    public function DeliveryStatus(){
        $where = [];
        $where[]  = ['createtime', '>=', 1748707200];
        $where[]  = ['createtime', '<=', time()];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['tracking_number', 'like', "%DYY%"];
        $where[]  = ['shipment_status', '=', ''];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $lists = Db::name('order_achievement')
                ->field('id,order_id,tracking_number as track_number,createtime,financial_status,fulfillment_status')
                ->where($where)
                ->limit(500)
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
        
            foreach($lists['data'] as $k=>$v){
                //方法1
                // $order_webhooks = Db::name('order_webhooks')->where('order_id',$v['order_id'])->order('id desc')->find();
                // if(empty($order_webhooks['json'])){ 
                //     continue;
                // }
                // $order = json_decode($order_webhooks['json'],true);
                // $shipment_status = $order['fulfillments'][0]['shipment_status'] ?? "";
                // Db::name('order_achievement')->where('id',$v['id'])->update(['shipment_status' => $shipment_status]);

                //方法2
                // $status = $this->trackLogisticsTrajectory($v['track_number']);
                // $this->updateOrderLogisticsStatus($v,$status);
                // $executedCount++;
                // $num = $count - $executedCount;
                // // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页,当前订单'.$v['order_id']."的物流状态是".$status . PHP_EOL;

                //方法3 dyy
                $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('id desc')->find();
                $status = $order_track['latest_status'] ?? "";
                if(!empty($status)){ 
                    // $status = $track_status;
                }else{
                    $number = $v['track_number'];
                    $OrderLogic = new OrderLogic();
                    $result = $OrderLogic->curlRequest('http://43.139.12.243:8082/selectTrack.htm', "documentCode=".$number);
                    $resultData = json_decode($result['result'], true);
                    $status = $resultData[0]['data'][0]['businessStatus'] ?? "";
                }
                if(!empty($status)){
                    $this->updateOrderLogisticsStatus($v,$status);

                    switch ($status) {
                        case '签收':
                            $status_info = 'delivered';
                            break;
                        case '转运中':
                            $status_info = 'in_transit';
                            break;
                        // case '收货':
                        //     $status_info = 'delivered';
                        //     break;
                        case '投递失败':
                            $status_info = 'failure';
                            break;
                        case '退仓':
                            $status_info = 'failure';
                            break;
                        default:
                            $status_info = '';
                        if(empty($status_info)){
                            Db::name('order_achievement')->where('id',$v['id'])->update(['shipment_status' => $status_info]);
                        }
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页,当前订单'.$v['order_id']."的物流状态是".$status . PHP_EOL;

            }
        }
    }

    
    //配送状态
    public function DeliveryStatus4px(){
        $where = [];
        $where[]  = ['createtime', '>=', 1748707200];
        $where[]  = ['createtime', '<=', time()];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['fulfillment_status', '=', "fulfilled"];
        $where[]  = ['tracking_number', 'like', "%4px%"];
        $where[]  = ['shipment_status', '=', ''];
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $lists = Db::name('order_achievement')
                ->field('id,order_id,tracking_number as track_number,createtime,financial_status,fulfillment_status')
                ->where($where)
                ->limit(500)
                ->order('createtime desc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
        
            foreach($lists['data'] as $k=>$v){
                //方法1
                // $order_webhooks = Db::name('order_webhooks')->where('order_id',$v['order_id'])->order('id desc')->find();
                // if(empty($order_webhooks['json'])){ 
                //     continue;
                // }
                // $order = json_decode($order_webhooks['json'],true);
                // $shipment_status = $order['fulfillments'][0]['shipment_status'] ?? "";
                // Db::name('order_achievement')->where('id',$v['id'])->update(['shipment_status' => $shipment_status]);

                //方法2
                // $status = $this->trackLogisticsTrajectory($v['track_number']);
                // $this->updateOrderLogisticsStatus($v,$status);
                // $executedCount++;
                // $num = $count - $executedCount;
                // // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页,当前订单'.$v['order_id']."的物流状态是".$status . PHP_EOL;

                //方法3 dyy
                $order_track = Db::name('order_track')->where('order_id',$v['order_id'])->order('id desc')->find();
                $status = $order_track['latest_status'] ?? "";
                if(!empty($status)){ 
                    // $status = $track_status;
                }else{
                    $track_number = $v['track_number'];
                    $url                  = Config('Logisticskey.4px_track.url');
                    $param  = [
                        'method'          => Config('Logisticskey.4px_track.track_method'),
                        'app_key'         => Config('Logisticskey.4px_track.app_key'),
                        'v'               => '1.0.0',
                    ];
                    $signature_info   =  self::track_4px_sign($track_number);
                    $param['timestamp'] =  $signature_info['timestamp'];
                    $param['format']    =  'json';
                    $param['sign']      =  $signature_info['signature'];
                    $data             = [
                        'deliveryOrderNo'=>$track_number
                    ];
                    $signature_url      = urladdparam($url,$param);
                    $post               = HttpUtil::postDataCurl($signature_url,$data);
                    $track_number       = $post['data']['deliveryOrderNo']??'';
                    $tracking_list      = $post['data']['trackingList']??[];
                    $status_17_staus    = Config('Logisticskey.4px_track.4px_17_status');
                    //最新的物流主状态;
                    $current_info       =  current($tracking_list);
                    $result             =  $current_info['businessLinkCode']??'';
                    $status      =  $status_17_staus[$result]??'';
                }
                if(!empty($status)){
                    $this->updateOrderLogisticsStatus($v,$status);

                    switch ($status) {
                        case '签收':
                            $status_info = 'delivered';
                            break;
                        case '转运中':
                            $status_info = 'in_transit';
                            break;
                        // case '收货':
                        //     $status_info = 'delivered';
                        //     break;
                        case '投递失败':
                            $status_info = 'failure';
                            break;
                        case '退仓':
                            $status_info = 'failure';
                            break;
                        default:
                            $status_info = '';
                        if(empty($status_info)){
                            Db::name('order_achievement')->where('id',$v['id'])->update(['shipment_status' => $status_info]);
                        }
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                // echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页,当前订单'.$v['order_id']."的物流状态是".$status . PHP_EOL;

            }
        }
    }
    


    public function track_4px_sign($track_number){
        $microtime               = microtime(true);
        // 将微秒转换为毫秒
        $milliseconds            = round($microtime * 1000);
        // 输入的基本参数
        $params = [
            'app_key'   =>  Config('Logisticskey.4px_track.app_key'),
            'format'    => 'json',
            'method'    => Config('Logisticskey.4px_track.track_method'),
            'timestamp' => $milliseconds, // 当前时间戳，毫秒
            'v'         => '1.0.0',
            'body'      => json_encode(['deliveryOrderNo' => $track_number]), // 将 body 序列化为 JSON 字符串
        ];
        $app_secret = Config('Logisticskey.4px_track.app_secret');
       // 将参数拼接成签名字符串
        $signStr =
            'app_key' . $params['app_key'] .
            'format' . $params['format'] .
            'method' . $params['method'] .
            'timestamp' . $params['timestamp'] .
            'v' . $params['v'] .
            $params['body'] . // 使用序列化后的 JSON
            $app_secret; // 最后加上 App Secret
        // 计算 MD5 签名
        $generatedSign = md5($signStr);
        return ['signature'=>$generatedSign,'timestamp'=>$milliseconds];
    }


    /**
    * @desc    修改配送状态
    * @date    2025/6/16
    * @author  zhangheng
    */
    public function updateOrderLogisticsStatus($data,$latest_status)
    {
        switch ($latest_status) {
            case 'Delivered':
                $status = 'delivered';
                break;
            case '签收':
                $status = 'delivered';
                break;
            case '转运中':
                $status = 'in_transit';
                break;
            case 'InTransit':
                $status = 'in_transit';
                break;
            case 'InfoReceived':
                $status = 'confirmed';
                break;
            // case '收货':
            //     $status = 'delivered';
            //     break;
            case 'OutForDelivery':
                $status = 'out_for_delivery';
                break;
            case 'DeliveryFailure':
                $status = 'failure';
                break;
            case '投递失败':
                $status = 'failure';
                break;
            case 'AvailableForPickup':
                $status = 'ready_for_pickup';
                break;
            case '退仓':
                $status = 'failure';
                break;
            default:
                $status = '';
        }
        $order = Db::name('order_achievement')->where('tracking_number',$data['track_number'])->find();

        //日志
        $log = [
            'shipment_status' => $order['shipment_status'] ?? "",
            'order_id' => $order['order_id'] ?? 0,
            'shop_id' => $order['shop_id'] ?? 0,
            'shopify_status' => $status ?? "",
            'track_number' => $data['track_number'] ?? "",
            'latest_status' => $latest_status ?? "",
            'update_time'   => date("Y-m-d H:i:s", time()),
        ];
        //日志
        // halt($log);
        //开始修改配送状态
        $msg = '';
        $order_id = $log['order_id'];
        $shop_id = $log['shop_id'];
        $status = $log['shopify_status'];
        
        $shipment_status = $order['shipment_status'] ?? "";

        if(empty($order)){
            // $msg = '没有找到该订单';
            // //日志
            // $log['msg'] = $msg;
            // Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }

        // 从4月开始
        $createtime = $order['createtime'] ?? 0;
        if($createtime < time() - 86400 * 30*4){
            return true;
        }
        // 只要4px和dyy开头的
        if(strpos($data['track_number'], '4PX') === false && strpos($data['track_number'], 'DYY') === false){
            return true;
        }

        if(empty($status)){
            $msg = '状态不匹配,原状态'.$latest_status;
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        
        
        if($shipment_status == $status){
            $msg = '状态没变化不更新';
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        
        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments.json";
        // halt($log);
        $fulfillments = HttpUtil::getUrl($url, $shop_info);
        // halt($fulfillments);
        $fulfillment_id = $fulfillments['fulfillments'][0]['id'] ?? 0;
        if($fulfillment_id == 0){
            $msg = '没有可发货的订单';
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        //物流详情
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments/".$fulfillment_id."/events.json";
        //新增
        $data_fulfillment = [];
        $data_fulfillment['status'] = $status;
        $data_fulfillments = [
            'event' => $data_fulfillment
        ];
        $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
        $msg = $return;

        //日志
        $log['msg'] = $msg;
        Db::name('order_tracklog')->insert($log);
        //日志
        return true;
    }

}
